<template>
  <div class="header-wrapper">
    <div class="left">
      <div class="back" @click="navToList">
        <img src="../assets/left_arrow.webp" alt="" />
      </div>
      <div class="title">航空结构CAE</div>
    </div>
    <div class="right">
      <TabNav
        v-model:active="TabNavActive"
        style="height: 48px"
        @change="tabChange"
      >
        <TabNavItem
          :label="item.label"
          v-for="item in MenuType"
          :key="item.label"
        ></TabNavItem>
      </TabNav>
      <div class="tab-content-wrapper">
        <div
          class="flex"
          v-show="TabNavActive === '视图'"
          :style="floatWidthStyle"
        >
          <CommonTool :showCellIds="showCellIds"></CommonTool>
          <div class="line"></div>
          <ViewTool></ViewTool>
        </div>
        <div
          class="flex"
          v-show="TabNavActive === '几何处理'"
          :style="floatWidthStyle"
        >
          <CommonTool :showCellIds="showCellIds"></CommonTool>
          <div class="line"></div>
          <GeometryTool></GeometryTool>
          <div class="line"></div>
          <div class="block">
            <div class="flex">
              <div
                :class="showCellIds ? 'func-active' : 'func'"
                @click="chamferFace"
              >
                <img src="../assets/simainti.svg" alt="" class="icon" />
                <span class="func-name">倒圆角面</span>
              </div>
              <div class="fill"></div>
              <div
                :class="showCellIds ? 'func-active' : 'func'"
                @click="chamferEdge"
              >
                <img src="../assets/liumianti.svg" alt="" class="icon" />
                <span class="func-name">倒圆角边</span>
              </div>
              <div class="fill"></div>
              <div
                :class="showCellIds ? 'func-active' : 'func'"
                @click="chamferAngle"
              >
                <img src="../assets/liumianti.svg" alt="" class="icon" />
                <span class="func-name">倒棱角面</span>
              </div>
              <div
                :class="showCellIds ? 'func-active' : 'func'"
                @click="edgePartition"
              >
                <img src="../assets/liumianti.svg" alt="" class="icon" />
                <span class="func-name">边剖分</span>
              </div>
            </div>
            <div class="title">特征去除</div>
          </div>
        </div>
        <div
          class="flex"
          v-show="TabNavActive === '网格剖分'"
          :style="floatWidthStyle"
        >
          <CommonTool :showCellIds="showCellIds"></CommonTool>
          <div class="line"></div>
          <div class="block">
            <div class="flex">
              <div
                :class="showCellIds ? 'func-active' : 'func'"
                @click="setMesh"
              >
                <img src="../assets/common_mesh.svg" alt="" class="icon" />
                <span class="func-name">二维网格</span>
              </div>
              <div class="fill"></div>
              <div
                :class="showCellIds ? 'func-active' : 'func'"
                @click="setWasher"
              >
                <img src="../assets/common_mesh.svg" alt="" class="icon" />
                <span class="func-name">垫圈网格</span>
              </div>
              <div class="fill"></div>
              <div
                :class="showCellIds ? 'func-active' : 'func'"
                @click="setMesh"
              >
                <img src="../assets/center_mesh.svg" alt="" class="icon" />
                <span class="func-name">中面网格</span>
              </div>
              <div class="fill"></div>
              <div
                :class="showCellIds ? 'func-active' : 'func'"
                @click="resetMesh"
              >
                <img src="../assets/re_mesh.svg" alt="" class="icon" />
                <span class="func-name">重剖分</span>
              </div>
            </div>
            <div class="title">二维网格</div>
          </div>
          <div class="line"></div>
          <div class="block">
            <div class="flex">
              <div
                :class="showCellIds ? 'func-active' : 'func'"
                @click="setTetrahedron"
              >
                <img src="../assets/simainti.svg" alt="" class="icon" />
                <span class="func-name">四面体</span>
              </div>
              <div class="fill"></div>
              <div
                :class="showCellIds ? 'func-active' : 'func'"
                @click="setMesh"
              >
                <img src="../assets/liumianti.svg" alt="" class="icon" />
                <span class="func-name">六面体</span>
              </div>
              <div
                :class="showCellIds ? 'func-active' : 'func'"
                @click="setCFDMesh"
              >
                <img src="../assets/liumianti.svg" alt="" class="icon" />
                <span class="func-name">流体边界层网格</span>
              </div>
              <div
                :class="showCellIds ? 'func-active' : 'func'"
                @click="setWrapperMesh"
              >
                <img src="../assets/liumianti.svg" alt="" class="icon" />
                <span class="func-name">包面网格</span>
              </div>
            </div>
            <div class="title">三维网格</div>
          </div>
        </div>
        <div
          class="flex"
          v-show="TabNavActive === '网格检查'"
          :style="floatWidthStyle"
        >
          <CommonTool :showCellIds="showCellIds"></CommonTool>
          <div class="line"></div>
          <MeshCheckTool></MeshCheckTool>
        </div>
        <div
          class="flex"
          v-show="TabNavActive === '网格编辑'"
          :style="floatWidthStyle"
        >
          <CommonTool :showCellIds="showCellIds"></CommonTool>
          <div class="line"></div>
          <MeshEditTool></MeshEditTool>
        </div>
        <div
          class="flex"
          v-show="TabNavActive === '求解分析'"
          :style="floatWidthStyle"
        >
          <CommonTool :showCellIds="showCellIds"></CommonTool>
          <div class="line"></div>
          <SolverTool></SolverTool>
        </div>
        <div
          class="flex"
          v-show="TabNavActive === '工具'"
          :style="floatWidthStyle"
        >
          <CommonTool :showCellIds="showCellIds"></CommonTool>
          <div class="line"></div>
          <ExtraTool></ExtraTool>
        </div>
        <div
          class="flex"
          v-show="TabNavActive === '后处理'"
          :style="floatWidthStyle"
        >
          <CommonTool :showCellIds="showCellIds"></CommonTool>
          <div class="line"></div>
          <PostProcessingTool></PostProcessingTool>
        </div>
      </div>
      <FloatMenu />
    </div>
    <Modal
      v-model:active="fileSaveModalActive"
      transfer
      title="导出到模型库"
      width="30vw"
      @confirm="executeFileSave"
    >
      <Input value="case.bdf" placeholder="" />
      <!-- 录视频用 -->
      <div class="mt-10">
        <Select :options="tempOp"></Select>
      </div>
      <!-- <Input
        v-model:value="fileSavePath"
        placeholder="不填默认下载到minio"
      /> -->
      <Checkbox class="mt-20" v-model:checked="displayedOnly">仅展示</Checkbox>
    </Modal>
    <Modal
      v-model:active="exportModalActive"
      transfer
      title="导出其他"
      width="10vw"
      @confirm="exportFileSave(selectedFileType)"
    >
      <Select v-model:value="selectedFileType" :options="exportTypeOptions">
      </Select>
    </Modal>
    <Modal
      v-model:active="testModalActive"
      title="测试工具"
      hide-mask
      draggable
      no-footer
    >
      <!-- 测试按钮-->

      <div class="mb-20">
        <div class="mb-20">
          <Button type="error" @click="loadTestData"> 加载测试数据</Button>
          <Button type="primary" @click="executeMeshCreate"
            >二维网格剖分
          </Button>
          <Button type="primary" @click="clearMesh">清除网格</Button>
          <Button type="primary" @click="executeMask">隐藏选中面</Button>
          <Button type="primary" @click="executeUnmask">取消隐藏面</Button>
          <Button type="primary" @click="executeFaceFillet">倒圆角面</Button>
          <Button type="primary" @click="showEdgeColor">显示边类型</Button>
        </div>
        <div class="flex">
          <span>删除固体</span>
          <Select
            placeholder="网格类型"
            class="w-100"
            :options="deleteEntityType"
            v-model:value="entityType"
            @change="deleteEntitySelect"
          ></Select>
          <Button type="primary" @click="deleteEntity">确定删除</Button>
        </div>
        <div class="flex">
          <span>最小半径</span>
          <Input
            placeholder="最小半径"
            class="w-100"
            v-model:value="minRadius"
          />
          <span>最大半径</span>
          <Input
            placeholder="最大半径"
            class="w-100"
            v-model:value="maxRadius"
          />
          <Button type="primary" @click="executeAnalysisHole">分析</Button>
          <!-- <Button type="primary" @click="executeCounterBore">补孔</Button> -->
        </div>
        <div class="flex">
          <span>抽中面</span>
          <Input
            placeholder="中面位置"
            class="w-100"
            v-model:value="midLocation"
          />
          <Input
            placeholder="最大偏移量"
            class="w-100"
            v-model:value="midMaxoffset"
          />
          <Button type="primary" @click="executeChoosePart">选择实体</Button>
          <Button type="primary" @click="executeMidSurface">抽中面</Button>
        </div>
        <div class="flex">
          <span>修剪</span>
          <Select
            placeholder=""
            class="w-100"
            :options="trimToolType"
            :disabled="trimToolDisable"
            v-model:value="trimTool"
            @change="handleTrimToolChange"
          ></Select>
          <Button type="primary" @click="confirmTrimTool">确定修剪工具</Button>
          <Select
            placeholder=""
            class="w-100"
            :disabled="trimTargetDisable"
            :options="trimTargetType"
            v-model:value="trimTarget"
            @change="handleTrimTargetChange"
          ></Select>
          <Button type="primary" @click="confirmTrimTarget">确定目标</Button>
        </div>
        <div class="flex">
          <span>网格大小</span>
          <Input
            placeholder="网格大小"
            class="w-100"
            v-model:value="meshSize"
          ></Input>
        </div>
        <div class="flex">
          <span>网格类型</span>
          <Select
            placeholder="网格类型"
            class="w-100"
            :options="meshType"
            v-model:value="meshTypeValue"
          ></Select>
        </div>
      </div>
      <div>
        <Button type="error" @click="unselectAll()">取消选择</Button>
      </div>
    </Modal>
    <Modal
      v-model:active="measureBoxActive"
      title="测量"
      hide-mask
      draggable
      no-footer
    >
      <div>
        <Divider text-position="left"> 种类</Divider>
        <div>
          <RadioGroup v-model:value="curMeasurement">
            <Radio
              v-for="item in MEASUREMENTS"
              :label="item.label"
              :key="item.value"
            ></Radio>
          </RadioGroup>
        </div>
        <Divider text-position="left"> 操作</Divider>
        <div class="measure-tool">
          <RadioGroup v-model:value="measurementType">
            <Radio
              v-for="item in MEASUREMENT_TYPE"
              :label="item.label"
              :key="item.type"
            ></Radio>
          </RadioGroup>
        </div>
        <Divider text-position="left"> 选择对象</Divider>
        <div class=""></div>
      </div>
    </Modal>
    <Modal
      v-model:active="connectModalActive"
      title="连接(需要去引擎后台申请)"
      draggable
      @confirm="connectToServer"
    >
      <div class="flex w-400 mb-10">
        <span class="mr-10 w-200">请输入密钥</span>
        <Input class="w-200"></Input>
      </div>
      <div class="flex w-400 mb-10">
        <span class="mr-10 w-200">请输入节点域名</span>
        <Input class="w-200" v-model:value="serverUrl"></Input>
      </div>
      <div class="flex w-400">
        <span class="mr-10 w-200">请输入节点路径</span>
        <Input class="w-200" v-model:value="serverPath"></Input>
      </div>
    </Modal>
  </div>
  <ExportModelVue></ExportModelVue>
  <GridModalVue></GridModalVue>
  <WasherModalVue></WasherModalVue>
  <TetmeshModalVue></TetmeshModalVue>
  <ImportModalVue></ImportModalVue>
  <RemeshModalVue></RemeshModalVue>
  <MeshCheckModalVue></MeshCheckModalVue>
  <ElemEditModalVue></ElemEditModalVue>
  <FreeEdgeCheckModalVue></FreeEdgeCheckModalVue>
  <DocListModal></DocListModal>
  <ChamferFaceModalVue></ChamferFaceModalVue>
  <EdgePartitionModalVue></EdgePartitionModalVue>
  <OrganizedModalVue></OrganizedModalVue>
  <CFDMeshActiveModalVue></CFDMeshActiveModalVue>
  <OffsetActiveModalVue></OffsetActiveModalVue>
  <WrapperModalVue></WrapperModalVue>
  <SolverTaskModal />
  <SolverCardModal />
  <LoadStepModal />
  <RenumberCellModal />
  <SolverResultModal />
  <ImportCloudModal></ImportCloudModal>
  <ResultLibraryModal></ResultLibraryModal>
  <MeshQualityModal></MeshQualityModal>
</template>
<script setup lang="ts">
import { ref, defineEmits } from "vue";
import {
  Button,
  Dropdown,
  DropdownItem,
  Checkbox,
  Input,
  Modal,
  Select,
  RadioGroup,
  Radio,
  Divider,
  Message,
  TabNav,
  TabNavItem,
  Toast,
} from "cax-ui";
import { useCoreStore, _global, useFloatMenuStore } from "@/UI/store";
import { VertexPoint, VTActorRenderType } from "cax-base";
import { MODEL_TYPE, SelectedParts } from "@/FrontProcessing";
import { storeToRefs } from "pinia";
import { useRouter, useRoute } from "vue-router";
import { GyActor } from "@/FrontProcessing";
/** **********
 * * http请求
 * **********/
import { getProjectById } from "@/UI/api/projects";
/** **********
 * * UI组件导入
 * **********/
import CommonTool from "../components/Header/CommonTool.vue";
import ViewTool from "../components/Header/ViewTool.vue";
import ExportModelVue from "@/UI/views/modal/ExportModal.vue";
import EdgePartitionModalVue from "@/UI/views/modal/EdgePartitionModal.vue";
import OrganizedModalVue from "@/UI/views/modal/OrganizedModal.vue";
import GridModalVue from "../views/modal/GridModal.vue";
import WasherModalVue from "../views/modal/WasherModal.vue";
import WrapperModalVue from "../views/modal/WrapperModal.vue";

import TetmeshModalVue from "../views/modal/TetmeshModel.vue"; // 四面体网格
import RemeshModalVue from "../views/modal/RemeshModal.vue";
import ImportModalVue from "../views/modal/ImportModal.vue";
import MeshCheckModalVue from "../views/modal/MeshCheckModal.vue";
import ElemEditModalVue from "../views/modal/ElemEditModal.vue";
import FreeEdgeCheckModalVue from "../views/modal/FreeEdgeCheckModal.vue";
import { vtxlyLoader } from "cax-base";
import MeshEditTool from "../components/Header/MeshEditTool.vue";
import GeometryTool from "./Header/GeometryTool.vue";
import ChamferFaceModalVue from "../views/modal/ChamferFaceModal.vue";
import FloatMenu from "./Header/FloatMenu.vue";
import ImportCloudModal from "@/UI/views/modal/ImportCloudModal.vue";
import ResultLibraryModal from "@/UI/views/modal/ResultLibraryModal.vue";
import MeshQualityModal from "./ExtraTool/MeshQualityModal.vue";
/** **********
 * * 配置导入
 * **********/
import { MenuType } from "./Header/config";
import SolverTool from "./Header/SolverTool.vue";
import PostProcessingTool from "./Header/PostProcessingTool.vue";
import ExtraTool from "./Header/ExtraTool.vue";
import DocListModal from "./DocListModal.vue";
import SolverTaskModal from "@/UI/views/modal/SolverTaskModal.vue";
import SolverCardModal from "@/UI/views/modal/SolverCardModal.vue";
import LoadStepModal from "@/UI/views/modal/LoadStepModal.vue";
import RenumberCellModal from "@/UI/views/modal/RenumberCellModal.vue";
import SolverResultModal from "@/UI/views/modal/SolverResultModal.vue";
import { FloatMenuSignal } from "../config";
import CFDMeshActiveModalVue from "../views/modal/CFDMeshActiveModal.vue";
import OffsetActiveModalVue from "../views/modal/OffsetModal.vue";
import MeshCheckTool from "./Header/MeshCheckTool.vue";

const router = useRouter();
const route = useRoute();
const floatMenuStore = useFloatMenuStore();
const coreStore = useCoreStore();

floatMenuStore.sub((msg: any) => {
  switch (msg.type) {
    case FloatMenuSignal.MESH_SHOW_ALL:
      meshShowAll();
      break;
    case FloatMenuSignal.MESH_HIDE_ALL:
      meshHideAll();
      break;
    case FloatMenuSignal.GEO_POINT_MODE:
      toGeoPointMode();
      break;
    case FloatMenuSignal.GEO_LINE_MODE:
      toGeoLineMode();
      break;
    case FloatMenuSignal.GEO_FACE_MODE:
      toGeoFaceMode();
      break;
    case FloatMenuSignal.VIEW_FACE_MODE:
      floatMenuStore.keyActiveStatusMap.set(9, true);
      floatMenuStore.keyActiveStatusMap.set(10, false);
      floatMenuStore.keyActiveStatusMap.set(11, false);
      coreStore.Notify.next({
        event: FloatMenuSignal.VIEW_FACE_MODE,
      });
      break;
    case FloatMenuSignal.VIEW_LINE_MODE:
      floatMenuStore.keyActiveStatusMap.set(9, false);
      floatMenuStore.keyActiveStatusMap.set(10, true);
      floatMenuStore.keyActiveStatusMap.set(11, false);
      coreStore.Notify.next({
        event: FloatMenuSignal.VIEW_LINE_MODE,
      });
      break;
    case FloatMenuSignal.VIEW_POINT_MODE:
      floatMenuStore.keyActiveStatusMap.set(9, false);
      floatMenuStore.keyActiveStatusMap.set(10, false);
      floatMenuStore.keyActiveStatusMap.set(11, true);
      coreStore.Notify.next({
        event: FloatMenuSignal.VIEW_POINT_MODE,
      });
      break;
    default:
      break;
  }
});

function toGeoPointMode() {
  floatMenuStore.keyActiveStatusMap.set(3, true);
  floatMenuStore.keyActiveStatusMap.set(4, false);
  floatMenuStore.keyActiveStatusMap.set(5, false);
}

function toGeoLineMode() {
  floatMenuStore.keyActiveStatusMap.set(3, false);
  floatMenuStore.keyActiveStatusMap.set(4, true);
  floatMenuStore.keyActiveStatusMap.set(5, false);
}

function toGeoFaceMode() {
  floatMenuStore.keyActiveStatusMap.set(3, false);
  floatMenuStore.keyActiveStatusMap.set(4, false);
  floatMenuStore.keyActiveStatusMap.set(5, true);
}

function meshShowAll() {
  _global.Engine.mesh.show_all();
  floatMenuStore.keyActiveStatusMap.set(1, true);
  floatMenuStore.keyActiveStatusMap.set(2, false);
}

function meshHideAll() {
  _global.Engine.mesh.hide_all();
  floatMenuStore.keyActiveStatusMap.set(1, false);
  floatMenuStore.keyActiveStatusMap.set(2, true);
}

const deleteEntity = () => {
  _global.Engine.geometry.delete(entityType.value);
};

const confirmTrimTool = () => {
  console.log("确定修剪工具");
  trimTargetDisable.value = false;
  trimToolDisable.value = true;
  // _global.Engine.geometry.delete(entityType.value);
};

const confirmTrimTarget = () => {
  console.log("确定修剪目标");
  trimTargetDisable.value = true;
  // _global.Engine.geometry.delete(entityType.value);
};

const exportTypeOptions = [
  {
    label: "step",
    value: "step",
  },
  {
    label: "brep",
    value: "brep",
  },
  {
    label: "iges",
    value: "iges",
  },
  {
    label: "igs",
    value: "igs",
  },
  {
    label: "obj",
    value: "obj",
  },
  {
    label: "k",
    value: "k",
  },
  {
    label: "cgns",
    value: "cgns",
  },
  {
    label: "cdb",
    value: "cdb",
  },
  {
    label: "h5",
    value: "h5",
  },
];

const MEASUREMENTS = [
  {
    label: "距离",
    value: 1,
  },
];
const curMeasurement = ref("距离");
const entityType = ref(2);
const trimTool = ref(2);
const trimTarget = ref(2);
const trimTargetDisable = ref(true);
const trimToolDisable = ref(false);

const deleteEntityType = [
  {
    label: "点",
    value: 32,
  },
  {
    label: "线",
    value: 8,
  },
  {
    label: "面",
    value: 2,
  },
  {
    label: "实体",
    value: 1,
  },
];

const trimToolType = [
  {
    label: "点",
    value: 32,
  },
  {
    label: "线",
    value: 8,
  },
  {
    label: "面",
    value: 2,
  },
];

const trimTargetType = [
  {
    label: "面",
    value: 2,
  },
  {
    label: "实体",
    value: 1,
  },
];

const MEASUREMENT_TYPE = [
  {
    label: "点对点",
    type: 1,
  },
  {
    label: "点对边",
    type: 2,
  },
  {
    label: "点对面",
    type: 3,
  },
  {
    label: "面对面",
    type: 4,
  },
  {
    label: "边对边",
    type: 5,
  },
];
const TabNavActive = ref("视图");
const measurementType = ref("");

const testModalActive = ref(false);
const {
  fileSaveModalActive,
  exportModalActive,
  connectModalActive,
  serverUrl,
  serverPath,
} = storeToRefs(coreStore);

// 是否显示网格节点编号
const showCellIds = ref(false);

// 框选网格
const selectMeshByBoxStatus = ref(false);
// 框选网格交叉点
const selectMeshPointByBoxStatus = ref(false);

const meshSize = ref(undefined);
const meshTypeValue = ref(undefined);
const meshType = [
  {
    label: " ETri",
    value: "ETri",
  },
  {
    label: " QuadTri",
    value: "QuadTri",
  },
];

const minRadius = ref(0.0);
const maxRadius = ref(20.0);

const midLocation = ref(50.0);
const midMaxoffset = ref(0.0);
let selectedFileType = ref();
function deleteEntitySelect(value: number) {
  entityType.value = value;
  if (value === 1) {
    coreStore.setEngineState(2);
  } else if (value === 2) {
    coreStore.setEngineState(0);
  } else if (value === 8) {
    coreStore.setEngineState(3);
  } else {
    coreStore.setEngineState(1);
  }
}

function handleTrimToolChange(value: number) {
  trimTool.value = value;
  // if (value === 1) {
  //   coreStore.setEngineState(2);
  // } else if (value === 2) {
  //   coreStore.setEngineState(0);
  // } else if (value === 8) {
  //   coreStore.setEngineState(3);
  // } else {
  //   coreStore.setEngineState(1);
  // }
  coreStore.setEngineState(4);
  console.log("coreStore", coreStore);
}

function handleTrimTargetChange(value: number) {
  trimTarget.value = value;
  if (value === 1) {
    coreStore.setEngineState(2);
  } else if (value === 2) {
    coreStore.setEngineState(0);
  } else if (value === 8) {
    coreStore.setEngineState(3);
  } else {
    coreStore.setEngineState(1);
  }
}

function executeAnalysisHole() {
  Toast.loading({ content: "分析中", duration: 0 });
  _global.Engine.defeature
    .analysis_hole({
      minRadius: minRadius.value,
      maxRadius: maxRadius.value,
    })
    .then((result: SelectedParts[]) => {
      console.log("result", result);
      if (result && result.length > 0) {
        result.forEach((item: SelectedParts) => {
          console.log("item", item);
          item.faceIds.forEach((faceId: number) => {
            console.log("faceId", faceId);
            _global.Engine.selectFace(item.partId, faceId, null);
          });
        });
      }
    })
    .catch((err) => {
      Message.error(err);
    })
    .finally(() => {
      Toast.close();
    });
}

function executeFaceFillet() {
  Toast.loading({ content: "倒角中", duration: 0 });
  _global.Engine.defeature
    .face_fillet()
    .then((result: any) => {
      console.log("result", result);
      coreStore.setBomInfo(result);
      console.log("外部获取装配信息", result);
      if (result) {
        Message.success("倒角成功");
      }
    })
    .catch((err) => {
      Message.error(err);
    })
    .finally(() => {
      Toast.close();
    });
}
function showEdgeColor() {
  // _global.Engine.
}

function executeChoosePart() {
  // 选择实体
  coreStore.setEngineState(2);
}

function executeMidSurface() {
  Toast.loading({ content: "抽中面中", duration: 0 });
  _global.Engine.defeature
    .mid_surface({
      location: midLocation.value,
      maxoffset: midMaxoffset.value,
    })
    .then((result: any) => {
      console.log("result", result);
      coreStore.setBomInfo(result);
      if (result) {
        Message.success("抽取成功");
      }
    })
    .catch((err) => {
      Message.error(err);
    })
    .finally(() => {
      Toast.close();
    });
}

function menuSelect(labels: (string | number)[]) {
  if (labels.length > 0) {
    switch (labels[0]) {
      case "import_step":
        coreStore.setFileLoadModalActive(true);
        break;
      case "export_bdf":
        coreStore.setFileSaveModalActive(true);
        break;
      case "test_tool":
        testModalActive.value = true;
        break;
      case "close_node":
        _global.Engine.config.disconnect();
        break;
    }
  }
}

function setMesh() {
  console.log("网格剖分");
  coreStore.setGridModalVueActive(true);
}
function setCFDMesh() {
  console.log("CFD网格剖分");
  coreStore.setCFDGridModalVueActive(true);
}
function setWrapperMesh() {
  console.log("包装");
  coreStore.setWrapperModalActive(true);
}

function setWasher() {
  // 垫圈网格
  coreStore.setWasherModalVueActive(true);
}

// 四面体
function setTetrahedron() {
  console.log("四面体~");
  coreStore.setTetrahedronModalVueActive(true);
}

function resetMesh() {
  console.log("网格重剖分");
  coreStore.setRemeshModalVueActive(true);
}

// 特征去除
function chamferFace() {
  console.log("倒圆角面");
  coreStore.setChamferFaceModalVueActive(true);
}
function edgePartition() {
  coreStore.setEdgePartitionModalVueActive(true);
}
function chamferEdge() {
  console.log("倒圆角边");
  coreStore.setChamferEdgeModalVueActive(true);
}
function chamferAngle() {
  console.log("倒棱角面");
  coreStore.setChamferAngleModalVueActive(true);
}

let res = ref({});

const fileSavePath = ref("");
const displayedOnly = ref(false);

function executeFileSave() {
  // TODO 临时注销
  _global.Engine.file
    .save({
      Path: fileSavePath.value,
      DisplayOnly: displayedOnly.value ? 1 : 0,
    })
    .then((path: string) => {
      Message.info("导出成功");
      //     // window.open(path);
    });
}
// 导出文件名
function exportFileSave(toType: string) {
  console.log("要导出的文件类型", toType);
  let filename = coreStore.getFilename();
  _global.Engine.file.download(filename, toType).then((path: string) => {
    window.open(path);
  });
}

// 隐藏被选中的面
function executeMask() {
  _global.Engine.masker.mask();
}

// 取消隐藏面
function executeUnmask() {
  _global.Engine.masker.unmaskAll();
}

function executeMeshCreate() {
  Toast.loading({ content: "网格剖分中", duration: 0 });
  _global.Engine.mesh
    .create({
      surfaceMeshOptions: {
        meshSizePercentOfBBox: Number(meshSize.value),
        elemType: meshTypeValue.value,
      },
    })
    .then(() => {
      console.log("完成了");
      Toast.close();
    });
}

function clearMesh() {
  _global.Engine.mesh.clear().then(() => {
    console.log("删除网格成功！");
  });
  // _global.Engine.meshComp.clearMesh();
}

function loadTestData() {
  _global.Engine.file
    .load("/testData/counter_bore.json", MODEL_TYPE.TEST_GY)
    .then((itemDataStringArr: any) => {
      const GeoData = [];
      for (let i = 0; i < itemDataStringArr.length; i++) {
        GeoData.push(new vtxlyLoader(itemDataStringArr[i]));
      }
      GeoData.forEach((loader: any, index: number) => {
        console.log("loader", loader);

        const vertexs: VertexPoint[] = [];
        const tmp = [...loader.vertexsMap];
        tmp.forEach((t) => {
          vertexs.push({ id: t[0], XYZ: t[1] });
        });
        // @ts-ignore
        const model = new GyActor(loader.polyData, {
          vertexs,
          partId: index,
          edgeData: loader.edgeData,
        });
        model.setRenderType(VTActorRenderType.SURFACE);
        model.faceTrianglesMap = loader.faceTrianglesMap;
        model.faceIds = loader.gyData.faceIds;
        model.normalsOn();
        _global.Engine.model.add(model);
      });
    });
}

const measureBoxActive = ref(false);

function measure() {
  return 0;
}

function changeShowCellIdsStatus() {
  if (showCellIds.value) {
    showCellIds.value = false;
    _global.Engine.meshComp.hindSeletedCellIds();
  } else {
    showCellIds.value = true;
    _global.Engine.meshComp.showSelectedCellIds();
  }
}

function unselectAll() {
  _global.Engine.selector.clearAll();
}

function connectToServer() {
  listen();
  _global.Engine.config.connect(
    "web_client",
    serverUrl.value,
    serverPath.value
  );
}

let isListening = 0;

function listen() {
  if (isListening === 0) {
    _global.Engine.hooks.onConnected(() => {
      Message.success("连接成功");
      loadProject();
    });
    _global.Engine.hooks.onDisconnected(() => {
      Message.error("连接断开");
    });
    isListening = 1;
  }
}

/**
 * @description 获取精确功能栏宽度
 */
function getFloatWidth() {
  const clientW = document.body.clientWidth - 385;
  return clientW + "px";
}

/**
 * @description 加载远程工程
 */
function loadProject() {
  // todo 暂时不走这个逻辑
  // if (!route.query.id) {
  //   Message.warning("没有工程ID,仅可作为临时空间使用");
  //   return;
  // }
  // Toast.loading({
  //   content: "加载中",
  //   duration: -1,
  // });
  // getProjectById(route.query.id as string)
  //   .then((res: any) => {
  //     if (res.status === "success" && res.data) {
  //       coreStore.setProjectInfo(res.data);
  //     }
  //     if (
  //       coreStore.projectInfo.projectContent.url &&
  //       coreStore.projectInfo.projectContent.url !== ""
  //     ) {
  //       return _global.Engine.project.load(
  //         coreStore.projectInfo.projectContent.url
  //       );
  //     }
  //   })
  //   .then(() => {
  //     return _global.Engine.model.info();
  //   })
  //   .then((info) => {
  //     coreStore.setBomInfo(info);
  //     Toast.close();
  //   });
}

const floatWidthStyle = { width: getFloatWidth() };

/**
 * @description 回到首页
 */
function navToList() {
  router.push({
    name: "projects",
  });
}

// 添加defineEmits来定义emit函数
const emit = defineEmits(["meshEdit"]);

/**
 * @description tab切换事件
 * @param v
 */
function tabChange(v: string) {
  if (v === "网格编辑") {
    emit("meshEdit", true);
  } else {
    emit("meshEdit", false);
  }
  if (v === "求解分析") {
    coreStore.changeComponentView("求解分析");
  } else if (v === "后处理") {
    coreStore.changeComponentView("后处理");
  } else {
    coreStore.changeComponentView("前处理");
  }
}
const tempOp = [
  {
    label: "sh-dc/input",
    value: "sh-dc/input",
  },
  {
    label: "d3-engine/model",
    value: "d3-engine/model",
  },
];
</script>
<style scoped lang="less">
@import "../styles/HeaderComp.less";
</style>
